import React, { useState } from 'react'
import { Button, Input, Typography, Space, Form, Card, message } from 'antd'

const { Title } = Typography

const App = () => {
  const [currentNumber, setCurrentNumber] = useState(null)
  const [form] = Form.useForm()

  // 生成随机数（-128到127之间的整数）
  const generateRandomNumber = () => {
    const number = Math.floor(Math.random() * 256) - 128
    setCurrentNumber(number)
    form.resetFields()
  }

  // 将十进制数转换为8位二进制
  const decimalToBinary = (num) => {
    const binary = Math.abs(num).toString(2)
    return binary.padStart(7, '0')
  }

  // 计算原码
  const getOriginalCode = (num) => {
    if (num >= 0) {
      return '0' + decimalToBinary(num)
    }
    return '1' + decimalToBinary(num)
  }

  // 计算反码
  const getInverseCode = (num) => {
    if (num >= 0) {
      return getOriginalCode(num)
    }
    const originalCode = getOriginalCode(num)
    return originalCode[0] + originalCode.slice(1).split('').map(bit => bit === '0' ? '1' : '0').join('')
  }

  // 计算补码
  const getComplementCode = (num) => {
    if (num >= 0) {
      return getOriginalCode(num)
    }
    const inverseCode = getInverseCode(num)
    let carry = 1
    const result = inverseCode[0] + inverseCode.slice(1).split('').reverse().map(bit => {
      if (carry === 0) return bit
      if (bit === '0') {
        carry = 0
        return '1'
      }
      return '0'
    }).reverse().join('')
    return result
  }

  // 计算移码
  const getOffsetCode = (num) => {
    const complement = getComplementCode(num)
    return (complement[0] === '0' ? '1' : '0') + complement.slice(1)
  }

  // 检查答案
  const checkAnswer = (values) => {
    if (currentNumber === null) {
      message.warning('请先生成一个随机数')
      return
    }

    const correctAnswers = {
      originalCode: getOriginalCode(currentNumber),
      inverseCode: getInverseCode(currentNumber),
      complementCode: getComplementCode(currentNumber),
      offsetCode: getOffsetCode(currentNumber)
    }

    const results = Object.entries(values).map(([key, value]) => {
      const isCorrect = value === correctAnswers[key]
      return { key, isCorrect, correct: correctAnswers[key] }
    })

    const allCorrect = results.every(r => r.isCorrect)

    if (allCorrect) {
      message.success('恭喜你，全部答对了！')
    } else {
      message.error('有错误答案，请检查：')
      results.forEach(({ key, isCorrect, correct }) => {
        if (!isCorrect) {
          message.error(`${key === 'originalCode' ? '原码' : 
                         key === 'inverseCode' ? '反码' : 
                         key === 'complementCode' ? '补码' : '移码'}
                       正确答案应为：${correct}`)
        }
      })
    }
  }

  return (
    <div className="container">
      <Title level={2} className="title">真值到机器数转换练习</Title>
      <Card>
        <Space direction="vertical" style={{ width: '100%' }}>
          <Button type="primary" onClick={generateRandomNumber}>
            生成随机数
          </Button>
          {currentNumber !== null && (
            <Title level={3}>当前数字：{currentNumber}</Title>
          )}
          <Form
            form={form}
            onFinish={checkAnswer}
            layout="vertical"
          >
            <Form.Item
              label="原码"
              name="originalCode"
              rules={[{ required: true, message: '请输入原码' },
                     { pattern: /^[01]{8}$/, message: '请输入8位二进制数' }]}
            >
              <Input placeholder="请输入8位二进制原码" />
            </Form.Item>
            <Form.Item
              label="反码"
              name="inverseCode"
              rules={[{ required: true, message: '请输入反码' },
                     { pattern: /^[01]{8}$/, message: '请输入8位二进制数' }]}
            >
              <Input placeholder="请输入8位二进制反码" />
            </Form.Item>
            <Form.Item
              label="补码"
              name="complementCode"
              rules={[{ required: true, message: '请输入补码' },
                     { pattern: /^[01]{8}$/, message: '请输入8位二进制数' }]}
            >
              <Input placeholder="请输入8位二进制补码" />
            </Form.Item>
            <Form.Item
              label="移码"
              name="offsetCode"
              rules={[{ required: true, message: '请输入移码' },
                     { pattern: /^[01]{8}$/, message: '请输入8位二进制数' }]}
            >
              <Input placeholder="请输入8位二进制移码" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                检查答案
              </Button>
            </Form.Item>
          </Form>
        </Space>
      </Card>
    </div>
  )
}

export default App